{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Introduction\n",
    "You are given a list of n-1 integers and these integers are in the range of 1 to n. There are no duplicates in list. One of the integers is missing in the list.\n",
    "\n",
    "# Approach 1\n",
    "\n",
    "1. Get the sum of numbers\n",
    "\n",
    "       total = n*(n+1)/2\n",
    "2. Subtract all the numbers from sum and you will get the missing number."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "data = [1, 2, 3, 4, 5, 6, 8]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def find_missing_number(data):\n",
    "    ans = ((len(data) + 1) * (len(data) + 2)) / 2\n",
    "    for x in data:\n",
    "        ans -= x\n",
    "    return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "7\n"
     ]
    }
   ],
   "source": [
    "print find_missing_number(data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Approach 2\n",
    "\n",
    "1) XOR all the array elements, let the result of XOR be X1.\n",
    "\n",
    "2) XOR all numbers from 1 to n, let XOR be X2.\n",
    "\n",
    "3) XOR of X1 and X2 gives the missing number."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def find_missing_number_xor(data):\n",
    "    a = data[0]\n",
    "    for x in data[1:]:\n",
    "        a ^= x\n",
    "    b = 1\n",
    "    for i in xrange(2, len(data) + 2):\n",
    "        b ^= i\n",
    "    return a ^ b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "7\n"
     ]
    }
   ],
   "source": [
    "print find_missing_number_xor(data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# References\n",
    "- http://www.geeksforgeeks.org/find-the-missing-number/\n",
    "- http://practice.geeksforgeeks.org/problems/missing-number-in-array/0"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
